import { useContext, useEffect, useState } from 'react'
import { PlaygroundContext } from '../../../ReactPlayground/PlaygroundContext'
import styles from './index.module.scss'
import FileNameItem from './FileNameItem'
import { ENTRY_FILE_NAME } from '../../../ReactPlayground/files'
export default function FileNameList() {
  const {files,selectedFileName,setSelectedFileName,addFile,removeFile,updateFileName,} = useContext(PlaygroundContext)
  const [tabs,setTabs] = useState<string[]>([])
  const [creating,setCreating] = useState<boolean>(false)
  useEffect(() => {
    setTabs(Object.keys(files))
  }, [files])
  const handleEditComplete = (name: string, prevName: string) => {
    updateFileName(prevName,name)//更新文件名
    setSelectedFileName(name)//更新选中的文件名
  }
  
  const addTab = () => {
    const newFileName = 'Comp'+Math.random().toString().slice(2,4)+'.tsx'
    addFile(newFileName)
    setSelectedFileName(newFileName)
    setCreating(true)
  }
  const handleRemove = (name: string) => {
    if (window.confirm('确定删除吗？')) {
      removeFile(name)
      setSelectedFileName(ENTRY_FILE_NAME)
    }
  }
  return (
    <div className={styles['tabs']} >
      {
        tabs.map((tab,index,arr) => (
          <FileNameItem 
            key={index} 
            onClick={()=>setSelectedFileName(tab)} 
            value={tab}
            creating={creating&&index===arr.length-1}//告诉子组件默认聚焦在最后一个组件
            actived={selectedFileName===tab} 
            onEditComplete={(name:string)=>{handleEditComplete(name,tab)}}
            onRemove={(e: React.MouseEvent)=>{
                e.stopPropagation()//阻止事件冒泡，阻止父组件的点击事件
                handleRemove(tab)
            }}
          ></FileNameItem>
        ))
      }
      <div className={styles['add']} onClick={addTab} style={{cursor:'pointer'}} >
        +
      </div>
    </div>
  )
}
